const extension = chrome.extension;
const port = extension.connect();
var isOn;
var isLoaded = false;
var numArticles = 0;
var tagMap = {};
var aTag = new Array();
var aTitle = new Array();
var aLink = new Array();
var aIntro = new Array();
var aImage = new Array();
var aDatePublished = new Array();
var respRss;
var tabID;

listenToState(port);
port.postMessage({});

function listenToState(port) {
    port.onMessage.addListener(function (data) {
        isOn = data.isOn;
        isLoaded = (data.respRSS != undefined);
        tagMap = {};
        if (isOn) {
            if (!isLoaded) {
                loadTags();
            } else {
                if (aTag.length == 0) loadRSSResponse(data.respRSS);
            }
        }
        highlightAll(isOn);
    });
}


function highlightAll(bHightlight) {
    var idCSS;
    $.each(
    aTag, function (i, objValue) {
        idCSS = 'jQueryLinkHeat' + i;
        if (bHightlight) {
            if ($('body a.' + idCSS).size() == 0) {
                $("body").highlight(objValue, {
                    element: 'a',
                    className: idCSS,
                    wordsOnly: true
                });
                $("." + idCSS).css({
                    backgroundColor: "#990000",
                    color: "#ffffff",
                    padding: "0 25px 0 2px",
                    backgroundImage: "url(http://gce-heat.googlecode.com/svn/trunk/icon.png)",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "right center"
                });
                $('body a.' + idCSS).qtipHeat({
                    content: '<h1 style=\'background: url(http://gce-heat.googlecode.com/svn/trunk/img/fondo-h1.gif); height: 47px; margin: 0; padding: 3px 0 0 0;\'><img style=\'display: block; margin: 0 0 0 11px;\' src=\'http://gce-heat.googlecode.com/svn/trunk/img/logo-heat.gif\' alt=\'Heat\'/></h1><div class=\'contenidosHeat\'><div class=\'izq\'><div class=\'dch\'><div class=\'bloqueHeat\'><a href=\'' + aLink[i] + '\' target=\'_blank\'><img src=\'' + aImage[i] + '\'/></a><p><a href=\'' + aLink[i] + '\' target=\'_blank\' class=\'titular\'>' + aTitle[i] + '</a><span class=\'pubDate\'>' + parseDate(aDatePublished[i]) + '</span>' + aIntro[i] + '<br/></p></div></div></div></div>',
                    position: {
                        corner: {
                            tooltip: 'bottomLeft',
                            target: 'topMiddle'
                        }
                    },
                    show: 'mouseover',
                    hide: 'mouseout',
                    style: {
                        width: 350,
                        padding: 0,
                        tip: true,
                        name: 'light'
                    },
                    show: {
                        effect: {
                            length: 0
                        }
                    },
                    hide: {
                        effect: {
                            length: 0
                        },
                        fixed: true
                    }
                })
            }

        } else {
            $("body").unhighlight({
                element: 'a',
                className: idCSS,
                wordsOnly: true
            });
        }

    });
}


function tagLoaded(tagName) {
    var resp = tagMap[tagName];
    if ((resp == "undefined") || (resp == undefined)) return false;
    else return true;
}

function loadRSSResponse(resp) {
    try {
        var idCSS;
        numArticles = 0;

        var start = new Date().getTime();
        var i = 0,
            limit = resp.Articles.length,
            busy = false;
        var processor = setInterval(function () {
            if (!busy) {
                busy = true;

                process(resp.Articles[i]);

                if (++i == limit) {
                    clearInterval(processor);
                }

                busy = false;
            }

        },
        100);
    }
    catch(e) {
        //alert("error:" + e.message + "]");
    }
}
function process(Article) {
            for (var j = 0; j < Article.Metadata.length; j++) {
                if (Article.Metadata[j].Key == "Tag") {
                    var Tag = Article.Metadata[j].Value;
                    if (tagLoaded(Tag) == false) {
                        var Title = Article.Title;
                        var Link = Article.Permalink;
                        var Intro = Article.Intro;
                        var Image = Article.Images[1].Url;
                        var DatePublished = Article.DatePublished;
                        tagMap[Tag] = "1";

                        aTag[numArticles] = Tag;
                        aTitle[numArticles] = Title;
                        aLink[numArticles] = Link;
                        aIntro[numArticles] = Intro;
                        aImage[numArticles] = Image;
                        aDatePublished[numArticles] = DatePublished;

                        idCSS = 'jQueryLinkHeat' + numArticles;
                        if ($('body a.' + idCSS).size() == 0) {
                            if (!isLoaded) {
                                $("body").highlight(Tag, {
                                    element: 'a',
                                    className: idCSS,
                                    wordsOnly: true
                                });
                            }

                            $("." + idCSS).css({
                                backgroundColor: "#990000",
                                color: "#ffffff",
                                padding: "0 25px 0 2px",
                                backgroundImage: "url(http://gce-heat.googlecode.com/svn/trunk/icon.png)",
                                backgroundRepeat: "no-repeat",
                                backgroundPosition: "right center"
                            });
                            $('body a.' + idCSS).qtipHeat({
                                content: '<h1 style=\'background: url(http://gce-heat.googlecode.com/svn/trunk/img/fondo-h1.gif); height: 47x; margin: 0; padding: 3px 0 0 0;\'><img style=\'display: block; margin: 0 0 0 11px;\' src=\'http://gce-heat.googlecode.com/svn/trunk/img/logo-heat.gif\' alt=\'Heat\'/></h1><div class=\'contenidosHeat\'><div class=\'izq\'><div class=\'dch\'><div class=\'bloqueHeat\'><a href=\'' + Link + '\' target=\'_blank\'><img src=\'' + Image + '\'/></a><p><a href=\'' + Link + '\' target=\'_blank\' class=\'titular\'>' + Title + '</a><span class=\'pubDate\'>' + parseDate(DatePublished) + '</span>' + Intro + '<br/></p></div></div></div></div>',
                                position: {
                                    corner: {
                                        tooltip: 'bottomLeft',
                                        target: 'topMiddle'
                                    }
                                },
                                show: 'mouseover',
                                hide: 'mouseout',
                                style: {
                                    width: 350,
                                    padding: 0,
                                    tip: true,
                                    name: 'light'
                                },
                                show: {
                                    effect: {
                                        length: 0
                                    }
                                },
                                hide: {
                                    effect: {
                                        length: 0
                                    },
                                    fixed: true
                                }
                            })

                            numArticles++;
                        }
                    }
                }
            }
}

function loadTags() {
    chrome.extension.sendRequest({
        getData: "rss"
    },

    function (response) {
        respRss = response.rssData;
        loadRSSResponse(respRss);
    });
}

function parseDate(s) {
    var date = null;
    date = new Date(parseInt(s.replace("/Date(", "").replace(")/", ""), 10));
    return date.toUTCString();
}
extension.onConnect.addListener(function (port) {
    listenToState(port);
});